<template>
  <div class="dynamic-inputs">
    <div v-for="(item, index) in inputsValue" :key="index" class="input-item">
      <input
          v-model="inputsValue[index]"
          type="text"
          class="input-field"
          :placeholder="placeholder"
      />
      <button
          type="button"
          class="remove-btn"
          @click="removeInput(index)"
          :disabled="inputsValue.length <= minInputs"
      >
        删除
      </button>
    </div>
    <button type="button" class="add-btn" @click="addInput" :disabled="inputsValue.length >= maxInputs">
      添加
    </button>
  </div>
</template>

<script setup>
import { computed,defineModel } from 'vue';

// 使用defineModel来创建双向绑定
const modelValue = defineModel('modelValue', { required: true });

// 接收其他props
const props = defineProps({
  minInputs: {
    type: Number,
    default: 1
  },
  maxInputs: {
    type: Number,
    default: Infinity
  },
  placeholder: {
    type: String,
    default: '请输入'
  }
});

// 计算属性用于处理输入值，保持双向绑定
const inputsValue = computed({
  get: () => {
    // 确保至少有一个输入框
    if (!modelValue.value || !modelValue.value.length) {
      return [''];
    }
    return modelValue.value;
  },
  set: (newValue) => {
    modelValue.value = newValue;
  }
});

// 添加新的输入框
function addInput() {
  if (inputsValue.value.length < props.maxInputs) {
    inputsValue.value = [...inputsValue.value, ''];
  }
}

// 删除指定索引的输入框
function removeInput(index) {
  if (inputsValue.value.length > props.minInputs) {
    inputsValue.value = inputsValue.value.filter((_, i) => i !== index);
  }
}
</script>

<style scoped>
.dynamic-inputs {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.input-item {
  display: flex;
  gap: 10px;
}

.input-field {
  flex: 1;
  padding: 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
}

.remove-btn {
  background-color: #ff6b6b;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 0 10px;
  cursor: pointer;
}

.remove-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}

.add-btn {
  background-color: #4caf50;
  color: white;
  border: none;
  border-radius: 4px;
  padding: 8px;
  cursor: pointer;
  margin-top: 5px;
}

.add-btn:disabled {
  background-color: #cccccc;
  cursor: not-allowed;
}
</style>
